package com.bzg.manager.controller.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.bzg.manager.controller.request.BodyReaderHttpServletRequestWrapper;
import com.bzg.manager.controller.request.HttpHelper;
import com.bzg.manager.controller.utils.VerifiUtil;

public class CRCFilter implements Filter{
	public static final Logger LOGGER = LoggerFactory.getLogger(CRCFilter.class);
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		    
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		//获取客户端ip
		String ip = httpServletRequest.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = httpServletRequest.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = httpServletRequest.getRemoteAddr();
	    }
	    
		ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
        String body = HttpHelper.getBodyString(requestWrapper);
        if (StringUtils.isBlank(body)) {
            LOGGER.error("=======来自ip：" + ip + "的请求被拒绝, 没有请求体！========");
            return;
        }
        JSONObject json;
        try{
        //使用Feature.OrderedField 使json字符串转为JSONObject时field顺序不改变！
        json = JSON.parseObject(body,Feature.OrderedField);
        }catch(Exception e){
        	e.printStackTrace();
        	LOGGER.error("==========Filter中请求体转换成JSONObject异常！===========");
        	return;
        }
        boolean flag = VerifiUtil.baseVerifity(json);
        if(!flag){
        	//CRC校验失败！
        	LOGGER.error("=======来自ip：" + ip + "的请求被拒绝, CRC校验失败！========");
        	return;
        }
        //校验成功后放行
        chain.doFilter(requestWrapper, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
